package com.yutel.amote.packet;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.util.Log;

import com.yutel.amote.service.ServerService;

public class ServerHelper extends Thread {
	final String TAG = "ServerHelper";
	private ServerSocket server;
	private ServerService s;

	public ServerHelper(int port, ServerService s) {
		try {
			server = new ServerSocket(port);
			this.s = s;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		Socket socket = null;
		ObjectInputStream in = null;
		try {
			while (true) {
				socket = server.accept();
				in = new ObjectInputStream(socket.getInputStream());
				AbstractPacket packet = (AbstractPacket) in.readObject();
				Log.d(TAG, packet.toString());
				// 屏幕操作
				if (Protocol.Command.click == packet.getCommand()) {
					s.sendMsg(packet.getValue());
				} else if(Protocol.Command.move == packet.getCommand()) {
					s.sendMsg(packet.getValue());
				} else {
					Log.e(TAG, packet.toString());
				}
				socket.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void finalize() {
		try {
			server.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		server = null;
	}
}
